﻿#include "datasourceterrain.h"
#include <QDir>
#include <fstream>
#include <osgDB/WriteFile>

rxtiler::DataSourceTerrain::DataSourceTerrain()
{

}


bool rxtiler::DataSourceTerrain::saveImage(rxtiler::TileKey &key, osg::Image *img)
{
    return false;
}


bool rxtiler::DataSourceTerrain::saveDEM(TileKey &key, osg::HeightField *dem)
{
    QDir _dir;
    //把int型的lod、y、x转化成QString四位，不够用0补齐
    //leftTustified,左对齐
    QString lstr = QString::number(key.lod);
    QString ystr = QString::number(key.y);
    QString xstr = QString::number(key.x);

    //创建目录，用“/”分隔
    QString str_dir = this->_path;
    str_dir += "/" + lstr;
    if(!_dir.exists(str_dir))
    {
        _dir.mkdir(str_dir);
    }

    str_dir += "/" + xstr;//2222
    if(!_dir.exists(str_dir))
    {
        _dir.mkdir(str_dir);
    }
    str_dir += "/" + ystr + ".terrain";


    int demsize = this->getTileSize();

    //向目录里存图片
    int fsize = demsize*demsize*sizeof(short)+2;
    short *s_dem = (short*)malloc(fsize);
    memset(s_dem,0,fsize);
    if(!_dir.exists(str_dir))
    {
        for( int y = 0; y < demsize; y++)
        {
            for(int x = 0; x < demsize; x++ )
            {
                float hv = dem->getHeight(x,demsize - 1 - y);

                s_dem[y*demsize+x] = (short)(hv + 1000) * 5;
            }
        }
    }
    //QFile输出多四个字节，为何？
    std::ofstream f(str_dir.toStdString(),std::ios::binary | std::ios::trunc);
    f.write((char*)s_dem, fsize);
    f.close();
    free(s_dem);

    return true;
}

void rxtiler::DataSourceTerrain::setSavePath(QString p){
    this->_root_dir = p;
}
